import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'
// 访问 store 页面
import store from '@/store'
const routes = [
  { path: '/test', component: () => import('@/views/Test') },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: () => import('@/views/Home/index.vue') },
      { path: '/category/:id', component: () => import('@/views/Category/index.vue') },
      { path: '/product/:id', component: () => import('@/views/Goods/index.vue') },
      { path: '/cart', component: () => import('@/views/cart/index.vue') },
      {
        path: '/settlement',
        component: () => import('@/views/Settlement')
      },
      {
        path: '/Pay',
        component: () => import('@/views/Pay/index.vue')
      },
      {
        path: '/Pay/callback',
        component: () => import('@/views/Pay/callback.vue')
      },
      {
        path: '/member',
        component: () => import('@/views/Member/Layout/index.vue'),
        children: [
          { path: '', component: () => import('@/views/Member/Home/index.vue') },
          // { path: '/member', component: () => import('@/views/Member/Home/index.vue') }, 可以省略
          // { path: '/member/order', component: () => import('@/views/Member/Home/index.vue') },
          { path: 'order', component: () => import('@/views/Member/Order/index.vue') }
        ]
      }
    ]
  },
  { path: '/login', component: () => import('@/views/Login/index.vue') },
  // 配置回跳组件
  {
    path: '/login/callback',
    component: () => import('@/views/Login/callback')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 滚动行为 https://next.router.vuejs.org/guide/advanced/scroll-behavior.html
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { behavior: 'smooth', top: 0 }
    }
  }
})
// 添加导航路由守卫
router.beforeEach((to, from, next) => {
  // 需要用户登录才能访问的网站都统一是 /member 开头
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    // 重新跳转到默认路径并且获取后面所携带的完整参数
    next('/login?redirectUrl=' + to.fullPath)
  } else {
    // 其他情况直接放行
    next()
  }
})
export default router
